<template>
  <div class="editorBox">
    <Toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode"/>
    <div class="mainEditor">
      <el-scrollbar height="100%">
        <Editor v-model="contentTemp"
                :defaultConfig="editorConfig"
                :mode="mode"
                @onCreated="onCreated"
                @onChange="onChange"
                @onDestroyed="onDestroyed"
        />
      </el-scrollbar>
    </div>
  </div>
</template>

<script>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
import {h, shallowRef} from "vue";
import {Boot} from '@wangeditor/editor'
import markdownModule from '@wangeditor/plugin-md'
import {mapActions, mapState} from "vuex";
export default {
  name: "MainEditor",
  props:['contentData'],
  components:{
    Editor, Toolbar
  },
  data(){
    return{
      toolbarConfig:{},
      editorConfig:{},
      editorRef:{},
      mode: 'default',
      editorContent:''
    }
  },
  computed:{
    ...mapState('editor',['content','contentTemp'])
  },
  methods:{
    ...mapActions('editor',['setContent','setContentTemp']),
    onCreated(editor){
      this.editorRef = editor
      // 初始化编辑内容
      if (this.editorContent!==''){
        editor.setHtml(this.editorContent)
      }
    },
    // 编辑器内容 调用
    onChange(editor){
      let html = editor.getHtml();
      console.log('html:',html)
      if (editor.getText()!==''){
        this.setContentTemp(html)
      } else {
        this.setContentTemp('')
      }
    },

    // 销毁调用
    onDestroyed(editor){
      let html = editor.getHtml();
      if (editor.getText()!==''){
        this.setContentTemp(html)
      } else {
        this.setContentTemp('')
      }
      editor.clear()
    }
  },
  beforeMount() {
    // 初始化编辑器配置
    this.editorContent=this.content
    this.editorRef = shallowRef()
    this.toolbarConfig = {}
    this.editorConfig={
      placeholder: '请输入内容...',
      MENU_CONF: {}
    }
    this.editorConfig.scroll = false
    // 添加 markdown 支持
    Boot.registerModule(markdownModule)

  },
  beforeUnmount() {
    if (this.editorRef!=null){
      this.editorRef.destroy()
    }
  },
  watch:{
    contentData:{
      handler(value){
          this.editorContent=value
      }
    }
  }
}
</script>

<style scoped>
.editorBox{
  height: 95%;
  background-color: #F5F7FA;
}
.mainEditor{
  height: 94%;
  overflow: auto;
}
</style>